<?php
Yii::import("SalesIdentity");
class SalesController extends Controller
{

    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('login'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('offerPrice','addGoodsComment'),
                'expression'=>array($this,'isSales'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );    
    }

    protected function isSales()
    {
        return !empty(CommonUtils::getSales());
    }

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
        );
    }
	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
    }

    /**
     * sales登录
     *
     */
    public function actionLogin() {
        $username = $_POST['username'];
        $password = $_POST['password'];

        $identity=new SalesIdentity($username,$password);
        if($user = $identity->authenticate()) {
          $duration=3600*24*30; // 30 days
          Yii::app()->user->login($identity,$duration);
          $_SESSION[_SESSIONID_SALES] = $user;
          echoToMobile("ok");
        }
        else
          echoToError(_ERROR_SALES_LOGIN);
    }

    /**
     * 出价
     */
    public function actionOfferPrice() {
       $gaid =  $_POST['gaid'];
        $price = (int)$_POST['price'];
       $auction = GoodsAuctioninfo::model()->findByPk(new MongoId($gaid));
       if ($auction->lowprice!=null && $auction->lowprice <= $price) {
           echoToError(_ERROR_SALES_OFFICEPRICE);
       }
       $sales = $auction->sales;
       $oldprice = $auction->lowprice;

       $auction->lowprice = (int)$price;
       $auction->sales = CommonUtils::getSalesId();
       $auction->save(false);

       try {
           $salesOffer= new SalesOffer();
           $salesOffer->goods = $auction->goods;
           $salesOffer->auction = (string)$auction->_id;
           $salesOffer->price = (int)$price;
           $salesOffer->offerTime = time();
           $salesOffer->sales =CommonUtils::getSalesId();
           $salesOffer->save(false);
       } catch(Exception $ex) {
           try {
               $auction->lowprice = (int)$oldprice;
               $auction->sales = (int)$sales;
               $auction->save(false);
           } catch(Exception $ex) {
               //TODO 记录日志
               Yii::getLogger()->log($ex->getMessage());
           }
           echoToError(_ERROR_SYSTEM_FAULT);
       }

       try {
           //写价格
           RedisCacheUtil::writePrice($auction->goods,$auction->lowprice);
       } catch(Exception $ex) {
           try {
               $auction->lowprice = $oldprice;
               $auction->sales = $sales;
               $auction->save(false);
           } catch(Exception $ex) {
               //TODO 记录日志
               Yii::getLogger()->log($ex->getMessage());
           }
           try {
               $salesOffer->delete();
           } catch(Exception $ex) {
               //TODO 记录日志
               Yii::getLogger()->log($ex->getMessage());

           }
           echoToError(_ERROR_SYSTEM_FAULT);
       }
       try {
           $this->updatePrice($auction->goods,$auction->lowprice);
       } catch(Exception $ex) {
           try {
               $auction->lowprice = $oldprice;
               $auction->sales = $sales;
               $auction->save(false);
           } catch(Exception $ex) {
               //TODO 记录日志
               Yii::getLogger()->log($ex->getMessage());
           }
           try {
               $salesOffer->delete();
           } catch(Exception $ex) {
               //TODO 记录日志
               Yii::getLogger()->log($ex->getMessage());

           }
           RedisCacheUtil::writePrice($auction->goods,$oldprice);
           echoToError(_ERROR_SYSTEM_FAULT);
       }
       echoToMobile("ok");
    }

    /**
     * 得到代理品牌的商品
     *
     * @param $shelfTime
     */
    public function actionGetGoods($shelfTime=-1) {

    }

    private function updatePrice($id,$price)
    {
        $this->updateIndex($id,'price',$price);
    }

    private function updateIndex($id,$key,$value)
    {
        $solrUtil = new SolrUtil(_SOLR_ADDRESS, _SOLR_GOODS_ZN);
        $data = $solrUtil->update(array('id' => $id,$key=>array('set'=>$value)));

        $solrUtil = new SolrUtil(_SOLR_ADDRESS, _SOLR_GOODS_EN);
        $data = $solrUtil->update(array('id' => $id,$key=>array('set'=>$value)));
    }


}